import { useRequest } from 'ahooks'
import { Select, type SelectProps } from 'antd'

type SearchSelectProps = Pick<
  SelectProps<string, { label: string; value: string }>,
  'value' | 'onChange' | 'placeholder' | 'style'
> & {
  dependencies?: React.DependencyList
  request(searchValue?: string): Promise<
    Array<{
      label: string
      value: string
      [key: string]: unknown
    }>
  >
}

export default function SearchSelect({
  request,
  dependencies = [],
  ...props
}: SearchSelectProps) {
  const {
    data: options = [],
    loading,
    run
  } = useRequest(request, {
    refreshDeps: dependencies,
    debounceWait: 300
  })

  return (
    <Select
      {...props}
      loading={loading}
      options={options}
      showSearch
      allowClear
      filterOption={false}
      onSearch={run}
      onClear={run}
      dropdownRender={(menu) => {
        return loading ? <div>查询中...</div> : menu
      }}
    ></Select>
  )
}
